import { asyncRoutes, constantRoutes } from '@/router/routes'

import api from '@/api'
import Layout from '@/layout/header-aside'

/**
 * Use meta.role to determine if the current user has permission
 * 判断数组里面是否有权限,且将符合条件的路由返回
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  // 如果有meta且有roles属性的话 则进行角色判断,没有的默认返回true
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * 根据权限过滤路由
 * @param routes asyncRoutes  就是一个路由列表对象 {router,children [ {router,children [ {router} ] } ] }
 * @param roles
 */
export function filterAsyncRoutes (routes, roles) {
  const res = []
  routes.forEach(route => {
    // 将路由数组 拷贝给 temp
    const tmp = { ...route }
    // 判断路由是否有对应的角色
    if (hasPermission(roles, tmp)) {
      // 如果有子菜单继续判断
      if (tmp.children) {
        // 获取有权限的子菜单装进来
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      // 把当前菜单装进数组里面 也就是这个数组里面
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  // 在这里设置菜单 最终 在src\layout\components\Sidebar
  SET_ROUTES: (state, routes) => {
    // console.log('SET_ROUTES', routes)
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    // console.log('SET_ROUTES_Result', state.routes)
  }
}

const actions = {
  // 静态生成路由方法
  generateRoutes ({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      // 如果权限里面包含 admin的话 直接跳过判断，我这里是要通过后台返回路由，所以这一步暂时没有用了
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        // 如果没有特殊的权限,那么按照权限判断获取路由列表 这里传递进去的参数就是所有的动态路由菜单，现在修改成从后端传递过来所有的参数，那么这里就不需要进行判断，后端拿过来就是需要的菜单，这里仅仅需要访问后端接口就可以了
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  // 动态路由生产方法
  dynamicGenerateRoutes ({ commit }) {
    return new Promise(resolve => {
      api.LIST_MY_ROUTER().then(res => {
        const routers = tranfsforRouter(res)

        // 添加404页面
        commit('SET_ROUTES', routers)
        resolve(routers)
      })
    })
  }
}

export function tranfsforRouter (data) {
  const routers = data
  // const routers = JSON.parse(JSON.stringify(data))
  routers.forEach(router => {
    if (router.component === 'layout' || router.component === 'Layout') {
      router.component = Layout
    } else {
      const uri = router.component
      // var component = (resolve) => require([`@/views/${uri}.vue`], resolve)
      // var component = (resolve) => require([`@/views/${router.component}.vue`], resolve)
      // router.alwaysShow = false
      router.component = (resolve) => require([`@/views/${uri}.vue`], resolve)
    }
    if (router.children && router.children.length) {
      router.children = tranfsforRouter(router.children)
    }
  })
  return routers
}

// 路由懒加载
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}.vue`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
